<?php

namespace App\Services\Oauth;

use App\Core\Utils\TwHelper\CommFunction;
use App\Models\Oauth\UserModel;
use App\Exceptions\Response\Service\ServiceException;
use App\Exceptions\Response\Service\ServiceCode;
use App\Core\Utils\TwHelper\Random;
use App\Models\Club\MemberModel;
use App\Services\Oauth\User;
use App\Core\Entity\Message\MessageError;
use Illuminate\Support\Facades\Cookie;
use App\Services\Oauth\OauthorService;

class LoginService
{
    const ERROR_NUM_KEY = 'error_num_key';
    protected $mobile;
    protected $password;
    //验证码
    protected $verifyCode;

    protected $message;
    //登录错误的次数
    protected $errorCount = 0;

    public function __construct($mobile, $password, $verifyCode = '')
    {
        $this->mobile = $mobile;
        $this->password = $password;
        $this->verifyCode = $verifyCode;
    }

    /**
     * 登录
     */
    public function signIn()
    {
        //错误次数大于3次后就需要填入验证码,并验证
        if ($this->errorCount > 3) {
            if (!$this->verifyCode) {
                $this->setErrorCount();
                //验证码不能为空
                throw new ServiceException(ServiceCode::SERVICE_OAUTH_VERIFY_CODE_IS_NOT_NULL, '', []);
            }
            //校验验证码
            if (!captcha_check($this->verifyCode)) {
                $this->setErrorCount();
                throw new ServiceException(ServiceCode::SERVICE_OAUTH_VERIFY_CODE_WRONG, '', []);
            }
        }
        $user = UserModel::getUser($this->mobile);
        if (!$user) {
            $this->setErrorCount();
            throw new ServiceException(ServiceCode::SERVICE_USER_NOT_EXIST, '', []);
        }
        if (intval($user['status'] != UserModel::USER_STATUS_NOMAL)) {
            $this->setErrorCount();
            throw new ServiceException(ServiceCode::SERVICE_USER_STOP, '', []);
        }
        $makePassword = CommFunction::makePassword(trim($this->password), $user['key']);
        if ($makePassword == $user['password']) {
            //登录成功
            if (!$user['bbs_uid']) {
                $bbsUserName = CommFunction::createBbsUserName($user['username']);
                //创建bbs帐号
              //  $this->addBbsUserAccount($user['id'], $bbsUserName, $user['mobile'], $makePassword, $user['key']);
            } else {
                if (!MemberModel::getUserByUid($user['bbs_uid'])) {
                    $bbsUserName = CommFunction::createBbsUserName($user['username']);
                  //  $this->addBbsUserAccount($user['id'], $bbsUserName, $user['mobile'], $makePassword, $user['key']);
                }
            }
            //将查询到的用户信息传入给封装的用户类
            $userService = new User($user);
            if ($userService->checkUser()) {
                //用户登录时判断是否设置了地理信息，如果没有自动设置一个
                $userService = new UserService();
                $userService->addUserProfile($user['id']);
                //登录成功
                $data['user'] = $user;
                $data['message'] = 'login success';
                return $data;
            } else {
                $this->setErrorCount();
                throw new ServiceException(ServiceCode::SERVICE_USER_LOGIN_FAIL, '', []);
            }
        } else {
            $this->setErrorCount();
            throw new ServiceException(ServiceCode::SERVICE_USER_WRONG_PASSWORD, '', []);
        }
    }

    /**
     * 快速登录
     */
    public function shortSignIn($nationCode)
    {
        $user = UserModel::getUser($this->mobile);
        if (!$user) {
            //该用户不存在，创建新的帐号
            $data = array();
            $randomKey = CommFunction::makeRandomKey();
            //将随机码作为密码
            $makePassword = CommFunction::makePassword($randomKey, $randomKey);
            $username = CommFunction::createBbsUserName();
            $data['password'] = $makePassword;
            $data['key'] = $randomKey;
            $data['mobile'] = $this->mobile;
            $data['username'] = $username;
            //快捷登录
            $data['origin'] = 21;
            //国际电话区号
            //$data['nationCode'] = $nationCode;
            $data['status'] = UserModel::USER_STATUS_NOMAL;
            $data['created'] = $data['updated'] = time();
            //注册tongwei互联网帐号
            $id = UserModel::addUser($data);
            if ($id) {
                //根据注册时的ip获取到地理信息，并将省市保存到UserProfile表
                $registService = new RegistService();
                $registService->addUserProfile($id);
                //添加通心粉社区帐号
                $this->addBbsUserAccount($id, $username, $this->mobile, $makePassword, $randomKey);
            }
            $user = UserModel::getUser($this->mobile);
        } else {
            if (intval($user['status'] != UserModel::USER_STATUS_NOMAL)) {
                throw new ServiceException(ServiceCode::SERVICE_USER_STOP, '', []);
            }
        }
        //将查询到的用户信息传入给封装的用户类
        $userService = new User($user);
        if ($userService->checkUser()) {
            //用户登录时判断是否设置了地理信息，如果没有自动设置一个
            $userService = new UserService();
            $userService->addUserProfile($user['id']);
            //登录成功
            //第3方帐号绑定，建立关联关系
            //$oauthorService = new OauthorService();
            //$result = $oauthorService->addLoginOauth($id);
            return $user;
        } else {
            $this->setErrorCount();
            throw new ServiceException(ServiceCode::SERVICE_USER_LOGIN_FAIL, '', []);
        }
    }


    /*
     * 添加论坛的帐号
     */
    public function addBbsUserAccount($id, $username, $mobile, $password, $key)
    {
        $bbsId = MemberModel::signUp($mobile, $password, $username, $key);
        if ($id && $bbsId) {
            $data['bbs_uid'] = $bbsId;
            UserModel::updateUser($id, $data);
        }
    }

    /**
     * 设置登录失败的次数
     */
    public function setErrorCount()
    {
        $this->errorCount = $this->errorCount + 1;
        session()->put($this->getErrorNumKey(), $this->errorCount);
    }

    public function getErrorCount()
    {
        if (!$this->errorCount) {
            $this->errorCount = session()->get($this->getErrorNumKey()) ? session()->get($this->getErrorNumKey()) : 0;
        }
        return $this->errorCount;
    }

    /**
     * 清空登录失败的次数
     */

    public function unSetErrorCount()
    {
        $this->errorCount = 0;
        session()->forget($this->getErrorNumKey());
    }

    /**
     * 错误次数
     */
    public function getErrorNumKey()
    {
        return md5(self::ERROR_NUM_KEY);
    }

}